import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';

const $api = require('../../../../request/api').API;
Page({
  data: {
    selectionDialog: {
      show: false,
      data: [],
      selectedOptions: undefined,
      selectedOptionsIndex: 0
    },
    history: [],
    fireDesc: '',
    address: '',
    beeperId: '',
    selectorShow: false,
    selectedOptions: [],
    video: '',
    videoBase64: '',
    residentAddress: {
      fieldNames: {
        text: 'name',
        value: 'id'
      },
      name: '',
      columns: []
    }
  },
  onLoad: function (options) {
    const { beeperId } = options;
    this.setData({ beeperId });
    this.fetchResidentAddressList();
    this.fetchListRecentNotEndByBeeper(beeperId);
  },

  /**
   * 获取报警集合
   */
  fetchListRecentNotEndByBeeper(beeperId) {
    Toast.loading({ message: '加载中...', forbidClick: true });
    $api
      .listRecentNotEndByBeeper({ beeperId })
      .then(res => {
        Toast.clear();
        if (res.data.data.length === 1) {
          this.setData({ 'selectionDialog.data': res.data.data, 'selectionDialog.selectedOptions': res.data.data[0] });
          this.fetchListDataAlarmFire(res.data.data[0].alarmId);
        }

        if (res.data.data.length > 1) {
          this.setData({
            'selectionDialog.show': true,
            'selectionDialog.data': res.data.data,
            'selectionDialog.selectedOptions': res.data.data[0]
          });
        }

        if (res.data.data.length === 0) {
          Dialog.alert({ title: '提示', message: `24小时内无火灾报警，无需上报` }).then(() => {
            wx.navigateBack({ delta: 1 });
          });
        }
      })
      .catch(() => {
        Toast.clear();
      });
  },

  /**
   * 报警集合选择确认
   */
  handleDialogConfirm() {
    const { selectionDialog } = this.data;
    this.fetchListDataAlarmFire(selectionDialog.selectedOptions.alarmId);
  },

  /**
   * 根据报警id查询火情上报历史集合
   * @param alarmId
   */
  fetchListDataAlarmFire(alarmId) {
    Toast.loading({ message: '加载中...', forbidClick: true });
    $api
      .ListDataAlarmFire({ alarmId })
      .then(res => {
        const history = res.data.data.map(c => {
          return {
            ...c,
            address: c.site + c.buildName + c.unitName + c.floorName + c.houseNumber
          };
        });
        this.setData({ history });
        Toast.clear();
      })
      .catch(() => {
        Toast.clear();
      });
  },

  /**
   * 发送上报
   */
  handleSendReport() {
    const { selectedOptions, residentAddress, address, fireDesc, videoBase64, selectionDialog } = this.data;
    if (!residentAddress.name && !address) {
      Toast.fail('所在楼层或详细位置必须填写一个');
      return false;
    }
    const params = {
      fireDesc,
      alarmId: selectionDialog.selectedOptions.alarmId,
      fireVideos: videoBase64,
      site: address
    };
    if (selectedOptions.length >= 1 && selectedOptions[0].id) {
      params.buildId = selectedOptions[0].id;
      params.buildName = selectedOptions[0].name;
    }
    if (selectedOptions.length >= 2 && selectedOptions[1].id) {
      params.unitId = selectedOptions[1].id;
      params.unitName = selectedOptions[1].name;
    }
    if (selectedOptions.length >= 3 && selectedOptions[2].id) {
      params.floorId = selectedOptions[2].id;
      params.floorName = selectedOptions[2].name;
    }
    if (selectedOptions.length >= 4 && selectedOptions[3].id) {
      params.houseNumberId = selectedOptions[3].id;
      params.houseNumber = selectedOptions[3].name;
    }
    Toast.loading({ message: '上报中...', forbidClick: true });
    $api
      .sendReportAlarmFire(params)
      .then(res => {
        Toast.success('上报成功');
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 800);
      })
      .catch(err => {
        Toast.fail(err.msg || '上报失败');
      });
  },

  /**
   * 选中弹出层中的报警项目
   */
  handleSelectDialogOption(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      'selectionDialog.selectedOptionsIndex': index,
      'selectionDialog.selectedOptions': this.data.selectionDialog.data[index]
    });
  },

  // 选择视频
  handleSelectAddVideo() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: res => {
        let tempFilePath = res.tempFiles[0].tempFilePath;
        const videoBase64 = wx.getFileSystemManager().readFileSync(res.tempFiles[0].tempFilePath, 'base64');
        this.setData({ video: tempFilePath, videoBase64 });
      }
    });
  },

  /**
   * 获取该小区下的楼顶至门牌号
   */
  fetchResidentAddressList() {
    const { beeperId } = this.data;
    $api.getResidentAddressList({ beeperId }).then(res => {
      this.setData({ 'residentAddress.columns': res.data.data });
    });
  },

  /**
   * 楼栋选择器选择
   */
  handleResidentAddressChange(e) {
    const { selectedOptions } = e.detail;
    const fieldValue = selectedOptions.map(option => option.text || option.name).join('/');

    this.setData({
      'residentAddress.name': fieldValue,
      selectedOptions: e.detail.selectedOptions.map(c => {
        return { id: c.id, name: c.name };
      })
    });
  },

  /**
   * 清空楼栋层选择数据
   */
  handleWipeOptionData() {
    this.setData({ 'residentAddress.name': '', selectedOptions: [] });
  },

  /**
   * 打开楼栋层选择器
   */
  showResidentAddressPopup() {
    this.setData({ selectorShow: true });
  },

  /**
   * 关闭楼栋层选择器
   */
  closeResidentAddress() {
    this.setData({ selectorShow: false });
  },

  /**
   * 详细位置输入
   * @param e
   */
  handleTextareaInput(e) {
    const { remark } = e.target.dataset;
    if (remark === 'address') this.setData({ address: e.detail.value });
    if (remark === 'fireDesc') this.setData({ fireDesc: e.detail.value });
  },

  /**
   * 清除视频
   */
  handleClearVideo() {
    this.setData({ video: '' });
  }
});
